<?php

namespace app\api\model;


use think\Model;
use app\index\model\Pdf;
use think\Db;

class VisaForm extends Model
{
    protected $table = 'visa_form';
    
    public function VisaDetails($order_id, $autograph)
    {
        $pdf = (new Pdf())->shi($order_id);
        
        if ($pdf) {
            $textDefault  = [];
            $background   = ROOT_PATHS . '/uploads/PDF/' . $order_id . '.png';//背景
            $img          = imagecreatefrompng($background);
            $img_info     = imagesy($img);
            $imageDefault = [
                'left' => 120,
                'top' => $img_info - 170,
                'right' => 0,
                'bottom' => 0,
                'width' => 100,
                'height' => 100,
                'opacity' => 50,
            ];
            if (file_exists($background)) {
                if (!empty($autograph) && (parse_url($autograph)['host'] == 'imgaes.yiniaoweb.com' || parse_url($autograph)['host'] == 'api.yiniaoweb.com')) {
                    $path = '/app/' . (new PollingModel())->file_exists_S3($autograph, ROOT_PATH . 'public/app/');
                } else {
                    $path = parse_url($autograph, PHP_URL_PATH);
                    
                }
                $config['image'][]['url'] = ROOT_PATHS . $path;
                $filename                 = ROOT_PATHS . '/ContractNumber/' . $order_id . '.jpg';
                Common::getbgqrcode($imageDefault, $textDefault, $background, $filename, $config);
                $ali = new Aliyunoss();
                if (file_exists($filename)) {
                    $oss_result = $ali->upload('contract/' . config('city') . '/' . $order_id . time() . '.jpg', $filename);
                    if ($oss_result['info']['http_code'] == 200) {
                        $path = parse_url($oss_result['info']['url'])['path'];
                        $this->addList($order_id, $pdf['capital_id'], $autograph, 'https://images.yiniao.co' . $path, 2);
                        db('capital')->whereIn('capital_id', $pdf['capital_id'])->update([
                            'signed' => 1,
                        ]);
                        
                        if (file_exists($filename)) {
                            unlink($filename);
                        };
                        if (file_exists($config['image'][0]['url'])) {
                            unlink($config['image'][0]['url']);
                        }
                        
                        
                    }
                }
                return 'https://images.yiniao.co' . $path;
            }
        }
    }
    
    
    /*
     * 添加数据
     */
    public function addList($order_id, $capital_id, $autograph = '', $path = '', $type = 1, $money = 0, $mainMoney = 0, $give_money = 0, $purchasin_money = 0, $duration, $paymentMethod,$coutMainMoenyDiscount=0,$coutMoenyDiscount=0)
    {
        
        $visaFormData  = $this->where('order_id', $order_id)->whereNull('signing_time')->order('id desc')->select();
        $order_setting = \db('order_setting')
            ->join('order', 'order.order_id=order_setting.order_id', 'left')
            ->field('if(order_setting.visa_form_confirm=1,0,1) as isNeedPaper,order.created_time,order_setting.payment_type')
            ->join('contract', 'order.order_id=contract.orders_id', 'left')
            ->where('order_setting.order_id', $order_id)->find();
        $order_setting['isNeedPaper']=0;
        if ($order_setting['created_time'] < 1660150844 || $order_setting['isNeedPaper'] ==1) {
            $capitalArray = $capital_id;
            if (!empty($visaFormData)) {
                $capital_idList = explode(',', array_column($visaFormData, 'capital_id')[0]);
                foreach ($capitalArray as $k => $li) {
                    foreach ($capital_idList as $o) {
                        if ($li == $o) {
                            unset($capitalArray[$k]);
                        }
                        
                    }
                }
            }
            
        }
        $list = [
            'visa_map' => $path,
            'capital_id' => implode(',', $capital_id),
            'autograph' => $autograph,
            'order_id' => $order_id,
            'money' => $money,
            'mainMoney' => $mainMoney,
            'share' => 0,
            'give_money' => $give_money,
            'duration' => $duration,
            'purchasin_money' => $purchasin_money,
            'payment_method' => $paymentMethod,
            'products_main_discount_money' => $coutMainMoenyDiscount,
            'products_purchasing_discount_money' => $coutMoenyDiscount,
        ];
        if ($order_setting['created_time'] < 1660150844 || $order_setting['isNeedPaper'] ==1) {
            $list['share'] = 2;
        }
        if (empty($visaFormData) || $order_setting['isNeedPaper'] = 1) {
            $list['creation_time'] = time();
            $list['title']         = '增项减项签证单';
            $this->save($list);
        } else {
            if ($type == 2) {
                $list['signing_time'] = time();
            }
            $list['money']           += $visaFormData[0]['money'];
            $list['mainMoney']       += $visaFormData[0]['mainMoney'];
            $list['give_money']      += $visaFormData[0]['give_money'];
            $list['duration']        += $visaFormData[0]['duration'];
            $list['purchasin_money'] += $visaFormData[0]['purchasin_money'];
            $this->where('id', $visaFormData[0]['id'])->update($list);
        }
        if ($order_setting['created_time'] < 1660150844 || $order_setting['isNeedPaper'] ==1) {
            
            if ($order_setting['payment_type'] == 1) {
                $give_money+=$coutMainMoenyDiscount;
                $purchasin_money+=$coutMoenyDiscount;
                $nodes = Db::connect(config('database.zong'))->table('order_payment_nodes')
                    ->join('payment', 'payment.payment_id=order_payment_nodes.payment_id', 'left')
                    ->where('order_id', $order_id)
                    ->order('id asc')
                    ->select();
                
                $capital             = \db('capital')->whereIn('capital_id', implode(',', $capitalArray))->where('give', 0)->field('sum(if(agency=0 && types=1,to_price,0)) as man,sum(if(agency=1 && types=1,to_price,0)) as an')->select();
                $order_paymentId     = [];
                $order_paymentIdLast = [];
                foreach ($nodes as $item) {
                    if ((($item['weixin'] == 6 || $item['weixin'] == 8 || $item['weixin'] == 1) && empty($item['cleared_time'])) || ($item['weixin'] == 2 && $item['success'] != 2 && !empty($item['weixin'])) || ($item['weixin'] != 6 && $item['weixin'] != 8 && $item['weixin'] != 1 && empty($item['weixin']))) {
                        $order_paymentId = $item;
                        break;
                    }
                }
                if(count($nodes)==1){
                    $order_paymentIdLast= $nodes[0];
                }else{
                    $order_paymentIdLast= $nodes[count($nodes)-1];
                }
                $node_status=1;
               if($order_setting['isNeedPaper'] ==1){
                   $node_status=2;
               }
                
              
                if ($paymentMethod == 1) {
                    Db::connect(config('database.zong'))->table('order_payment_nodes')->insert(['order_id' => $order_id, 'node_title' => '增项金额', 'node_money' => $mainMoney + $capital[0]['man'] - $give_money + $capital[0]['an'] + $money - $purchasin_money, 'node_money_main' => $capital[0]['man'] + $mainMoney - $give_money, 'node_money_agency' => $capital[0]['an'] + $money - $purchasin_money, 'node_status' => $node_status, 'node_code' => 4, 'node_pay_tips' => '此处为增项产生金额', 'create_time' => time(), 'trigger_time' => time()]);
                } elseif ($paymentMethod == 20) {
                    if (!empty($order_paymentId)) {
                        $node_pay_sort = $order_paymentId['node_pay_sort'] + 1;
                        //总计
                        $total = $order_paymentId['node_money'] + $capital[0]['man'] + $capital[0]['an'] - $give_money + $money + $mainMoney - $purchasin_money;
                        //代购
                        $pr = $order_paymentId['node_money_agency'] + $capital[0]['an'] + $money - $purchasin_money;
                        //主合同
                        $main = $order_paymentId['node_money_main'] + $capital[0]['man'] + $mainMoney - $give_money;
                        Db::connect(config('database.zong'))->table('order_payment_nodes_log')->insert(['order_payment_nodes_id' => $order_paymentId['id'], 'node_money_before' => $order_paymentId['node_money'], 'node_money_after' => $total, 'create_time' => time(), 'description' => '增项']);
                        Db::connect(config('database.zong'))->table('order_payment_nodes')->where('id', $order_paymentId['id'])->update(['node_money' => $total, 'node_money_main' => $main, 'node_money_agency' => $pr]);
                        
                    } else {
                        Db::connect(config('database.zong'))->table('order_payment_nodes')->insert(['order_id' => $order_id, 'node_title' => '增项金额', 'node_money' => $mainMoney + $capital[0]['man'] - $give_money + $capital[0]['an'] + $money, 'node_money_main' => $capital[0]['man'] + $mainMoney - $give_money, 'node_money_agency' => $capital[0]['an'] + $money, 'node_status' => $node_status, 'node_code' => 4, 'node_pay_tips' => '此处为增项产生金额', 'create_time' => time()]);
                    }
                } elseif ($paymentMethod == 3 || $paymentMethod == 2) {
                   
                    //  $node_pay_sort = $order_paymentIdLast['node_pay_sort'] + 1;
                    if($order_paymentIdLast['payment_id']==0){
                        //总计
                        $total = $order_paymentIdLast['node_money'] + $capital[0]['man'] + $capital[0]['an'] - $give_money + $money + $mainMoney - $purchasin_money;
                        //代购
                        $pr = $order_paymentIdLast['node_money_agency'] + $capital[0]['an'] + $money - $purchasin_money;
                        //主合同
                        $main = $order_paymentIdLast['node_money_main'] + $capital[0]['man'] + $mainMoney - $give_money;
                        Db::connect(config('database.zong'))->table('order_payment_nodes')->where('id', $order_paymentIdLast['id'])->update(['node_money' => $total, 'node_money_main' => $main, 'node_money_agency' => $pr]);
                    }else{
                        Db::connect(config('database.zong'))->table('order_payment_nodes')->insert(['order_id' => $order_id, 'node_title' => '增项金额', 'node_money' =>  $mainMoney + $capital[0]['man'] - $give_money + $capital[0]['an'] + $money - $purchasin_money, 'node_money_main' => $capital[0]['man'] + $mainMoney - $give_money, 'node_money_agency' => $capital[0]['an'] + $money - $purchasin_money, 'node_status' => $node_status, 'node_code' => $order_paymentIdLast['node_code']+1, 'node_pay_tips' => '此处为增项产生金额', 'create_time' => time()]);
                    }
                    
                }
            }
        }
        
        
    }
    
    
}
